<template>
  <div class="role">
    <page-search
      ref="searchRef"
      :search-config="searchConfig"
      @query-click="handleQueryClick"
      @reset-click="handleResetClick"
    ></page-search>
    <page-content
      ref="contentRef"
      :content-config="contentConfig"
      @ok="handleOk"
      @create-btn-click="handleCreateBtnClick"
      @edit-btn-click="handleEditBtnClick"
    >
      <template #createAt="scope">
        {{ formatUTC(scope.row[scope.prop]) }}
      </template>
      <template #updateAt="scope">
        {{ formatUTC(scope.row[scope.prop]) }}
      </template>
    </page-content>
    <page-modal :modal-config="modalConfig" :other-info="otherInfo" ref="modalRef" @ok="handleOk">
      <template #menuList>
        <el-tree
          ref="treeRef"
          :data="entireMenus"
          show-checkbox
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
          @check="handleElTreeCheck"
        />
      </template>
    </page-modal>
  </div>
</template>

<script setup lang="ts">
import PageSearch from '@/components/page-search/page-search.vue'
import PageContent from '@/components/page-content/page-content.vue'
import PageModal from '@/components/page-modal/page-modal.vue'
import searchConfig from './config/search.config'
import contentConfig from './config/content.config'
import modalConfig from './config/modal.config'
import usePageContent from '@/hooks/usePageContent'
import usePageModal from '@/hooks/usePageModal'
import usePageSearch from '@/hooks/usePageSearch'
import { formatUTC } from '@/utils/format'
import useMainStore from '@/store/main/main'
import { storeToRefs } from 'pinia'
import { nextTick, ref } from 'vue'
import type { ElTree } from 'element-plus'
import { mapMenuListToIds } from '@/utils/map-menu'

const { contentRef, handleQueryClick, handleResetClick } = usePageContent()
const { modalRef, handleCreateBtnClick, handleEditBtnClick } = usePageModal(
  newCallback,
  editCallback
)

const { searchRef, handleOk } = usePageSearch()

const mainStore = useMainStore()
const { entireMenus } = storeToRefs(mainStore)

const otherInfo = ref({})
function handleElTreeCheck(_: any, param: any) {
  // checkedKeys 全选的 key, halfCheckedKeys 半选的 key
  const menuList = [...param.checkedKeys, ...param.halfCheckedKeys]
  otherInfo.value = { menuList }
}

const treeRef = ref<InstanceType<typeof ElTree>>()
function newCallback() {
  nextTick(() => {
    treeRef.value?.setCheckedKeys([])
  })
}

function editCallback(itemData: any) {
  // console.log(itemData.menuList)

  const menuIds = mapMenuListToIds(itemData.menuList)
  console.log(menuIds)

  // 执 dialogVisible.value = true 时,也就是弹窗的渲染并不是实时的,如果直接给 treeRef 赋值,是不生效的(Dom 还未渲染,所以不生效)
  // 所以需要使用 nextTick 函数, 它可以在 DOM 更新完成后立即调用
  nextTick(() => {
    treeRef.value?.setCheckedKeys(menuIds)
  })
}
</script>

<style lang="less" scoped></style>
